using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using CurrencyConv.Core.SettingsManager;

namespace CurrencyConv.Core.RatesDownloader
{
	public interface IRatesDownloader
	{
		XDocument GetRatesFromWeb();
	}

	public class RatesDownloader : IRatesDownloader
	{
		private readonly ISettingsManager _settingsManager;

		public RatesDownloader(ISettingsManager settingsManager)
		{
			_settingsManager = settingsManager;
		}

		public XDocument GetRatesFromWeb()
		{
			CCSettings settings = _settingsManager.LoadSettings();
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(settings.RemoteSiteAddress);
			request.Timeout = 5000; //millisecconds

			XNode node;

			try
			{
				using (WebResponse response = request.GetResponse())
				using (Stream responseData = response.GetResponseStream())
				{
					string xmlString = new StreamReader(responseData).ReadToEnd();
					node = XDocument.Parse(xmlString);
				}

			}
			catch (Exception ex)
			{
				return null;
			}
			return node.Document;
		}
	}
}